package org.jeecg.modules.xj.villager.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.util.PmsUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserTenantMapper;
import org.jeecg.modules.xj.job.service.IXjJobService;
import org.jeecg.modules.xj.points.service.IXjPointsService;
import org.jeecg.modules.xj.qrcode.entity.XjQrCode;
import org.jeecg.modules.xj.qrcode.service.IXjQrCodeService;
import org.jeecg.modules.xj.utils.QRcodeUtil;
import org.jeecg.modules.xj.villager.entity.SysUserVO;
import org.jeecg.modules.xj.villager.service.VillagerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class VillagerServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements VillagerService {
    @Autowired
    private SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    private SysUserTenantMapper userTenantMapper;
    @Autowired
    private IXjPointsService xjPointsService;
    @Autowired
    private IXjQrCodeService xjQrCodeService;
    @Autowired
    private IXjJobService xjJobService;
    //文件保存的路径
//    @Value("${jeecg.path.upload}")
//    private static String uploadPath;
    private static String uploadPath;

    @Value("${jeecg.path.upload:}")
    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    //前端访问地址
    private static String domainUrlPc;
    @Value("${jeecg.domainUrl.pc}")
    public void setDomainUrlPc(String domainUrlPc) {
        this.domainUrlPc = domainUrlPc;
    }

    /**
     * 村民信息查询
     * @param req
     * @param queryWrapper
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public Result<IPage<SysUserVO>> getUserVillager(HttpServletRequest req, QueryWrapper<SysUser> queryWrapper, Integer pageSize, Integer pageNo) {
        Result<IPage<SysUserVO>> result = new Result<IPage<SysUserVO>>();
        //update-begin-Author:wangshuai--Date:20211119--for:【vue3】通过部门id查询用户，通过code查询id
        //部门ID
        String departId = req.getParameter("departId");
        if (oConvertUtils.isNotEmpty(departId)) {
            LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<>();
            query.eq(SysUserDepart::getDepId, departId);
            List<SysUserDepart> list = sysUserDepartMapper.selectList(query);
            List<String> userIds = list.stream().map(SysUserDepart::getUserId).collect(Collectors.toList());
            //update-begin---author:wangshuai ---date:20220322  for：[issues/I4XTYB]查询用户时，当部门id 下没有分配用户时接口报错------------
            if (oConvertUtils.listIsNotEmpty(userIds)) {
                queryWrapper.in("id", userIds);
            } else {
                return Result.OK();
            }
            //update-end---author:wangshuai ---date:20220322  for：[issues/I4XTYB]查询用户时，当部门id 下没有分配用户时接口报错------------
        }
        //用户ID
        String code = req.getParameter("code");
        if (oConvertUtils.isNotEmpty(code)) {
            queryWrapper.in("id", Arrays.asList(code.split(",")));
            pageSize = code.split(",").length;
        }
        //update-end-Author:wangshuai--Date:20211119--for:【vue3】通过部门id查询用户，通过code查询id

        //update-begin-author:taoyan--date:20220104--for: JTC-372 【用户冻结问题】 online授权、用户组件，选择用户都能看到被冻结的用户
        String status = req.getParameter("status");
        if (oConvertUtils.isNotEmpty(status)) {
            queryWrapper.eq("status", Integer.parseInt(status));
        }
        //update-end-author:taoyan--date:20220104--for: JTC-372 【用户冻结问题】 online授权、用户组件，选择用户都能看到被冻结的用户

        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne("username", "_reserve_user_external");
        queryWrapper.isNotNull("id_card");
        queryWrapper.eq("user_identity","0");//默认是0 查询村民
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = this.page(page, queryWrapper);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());

        /** 对象转换 */
        IPage<SysUserVO> pageListVo = new PageDTO<SysUserVO>();
        BeanUtils.copyProperties(pageList,pageListVo);
        List<SysUser> userList = pageList.getRecords();
        List<SysUserVO> userVOList = new ArrayList<>();
        userList.forEach(user ->{
            SysUserVO userVO = new SysUserVO();
            BeanUtils.copyProperties(user,userVO);
            userVOList.add(userVO);
        });
        pageListVo.setRecords(userVOList);

        //用户对应信息合集
        if (userIds != null && userIds.size() > 0) {
            pageListVo.getRecords().forEach(item -> {
                double num =0.0;
                try {
                    num = xjPointsService.getUserPoints(item.getId());
                } catch (Exception e) {
                    num=0.0;
                }
                item.setPoints(num);//积分
                item.setQrCode(xjQrCodeService.getQrCodeFile(item.getId()));//二维码
            });
        }

        result.setSuccess(true);
        result.setResult(pageListVo);
        return result;
    }

    /**
     * 用于已有数据进行初始化生成二维码信息
     * 二维码  ID <==>  用户ID
     * @param checkId
     * @param response
     * @throws Exception
     */
    @Override
    public void qrcodeAll(String checkId, HttpServletResponse response) throws Exception {
        XjQrCode xjQrCode = new XjQrCode();
        /**
         * 获取要生成的数据ID，根据ID拼接调用访问地址的方法URL
         * 保存信息到二维码管理数据库
         */
        String imageId = UUIDGenerator.generate();
        //图片保存的绝对路径
        String imagePath = uploadPath+"\\qrcode\\"+imageId+".jpg";
        //二维码存储的  URL
        String qrCodeUrl = domainUrlPc+"/qrCodePoints?checkId="+checkId;

        //拼成前端访问地址--->二维码外网访问的绝对路径
        xjQrCode.setId(checkId);
        xjQrCode.setAllUrl(qrCodeUrl);
        xjQrCode.setSourceId(checkId);
        xjQrCode.setImage(imageId);
        xjQrCode.setDirUrl(imagePath);
        xjQrCodeService.updateById(xjQrCode);

        BufferedImage image = QRcodeUtil.createImage(qrCodeUrl);
        //将图片写出到指定位置（复制图片）
        OutputStream ops = new FileOutputStream(new File(imagePath));
        ImageIO.write(image, "jpg", ops);
    }


}
